import React from 'react';
import { connect } from 'dva';
import { Modal, WingBlank } from 'antd-mobile';
import { routerRedux } from 'dva/router';
import styles from './ExamMainPage.less';
import moment from 'moment';
import { Helmet } from 'react-helmet';
import classnames from 'classnames';

const _ = require('lodash');

let timer;

class ExamPage extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      selectKey: '',
      time: props.location.query.exam_time + ':00',
      startTime: '',
      endTime: '',
    };
  }

  componentDidMount() {
    const startTime = moment().toISOString();
    this.props.fetch({
      filter: {
        ref_type: this.props.location.query.ref_type,
        ref_id: this.props.location.query.ref_id,
      },
    });
    this.props.startExam(startTime, this.props.location.query.ref_type, this.props.location.query.ref_id);
    this.setState({ startTime });
    timer = setInterval(() => {
      const time = this.caculateTime();
      this.setState({ time });
    }, 500);
  }

  componentWillUnmount() {
    clearInterval(timer);
  }

  onChange = (selectKey, examItem, page, total, skip) => {
    if (examItem.type === false) {
      const selectKey2 = this.state.selectKey;
      const arr = selectKey2.split(',').filter(item => item.length);
      const index = arr.indexOf(selectKey);
      if (index !== -1) {
        arr.splice(index, 1);
      } else {
        arr.push(selectKey);
      }
      this.setState({
        selectKey: arr.join(','),
      });
      this.props.doExam(arr.join(','), examItem, this.props.location.query.ref_type, this.props.location.query.ref_id);
    } else {
      this.setState({ selectKey });
      this.props.doExam(selectKey, examItem, this.props.location.query.ref_type, this.props.location.query.ref_id);

      setTimeout(() => {
        this.onChangePage(page, total, selectKey);
      }, 500);
    }
  };

  onChangePage = (page, total, selectKey) => {
    if (page <= 0) {
      return;
    }
    if (selectKey !== undefined) {
      if (!selectKey) {
        return;
      }
    }

    if (page !== total + 1) {
      this.props.fetch({
        filter: {
          ref_type: this.props.location.query.ref_type,
          ref_id: this.props.location.query.ref_id,
        },
        page,
      });
    } else {
      this.caculateTime2();
    }
    this.setState({ selectKey: '' });
    // this.props.getTrains(this.props.examLibName);
  }

  caculateTime = () => {
    const now = moment().valueOf();
    const endDate = moment(this.state.startTime).add(parseInt(this.props.location.query.exam_time), 'minutes').valueOf();
    const leftTime = endDate - now;
    const leftsecond = parseInt(leftTime / 1000);
    const day1 = Math.floor(leftsecond / (60 * 60 * 24));
    const hour = Math.floor((leftsecond - day1 * 24 * 60 * 60) / 3600);
    let minute = Math.floor((leftsecond - day1 * 24 * 60 * 60 - hour * 3600) / 60);
    let second = Math.floor(leftsecond - day1 * 24 * 60 * 60 - hour * 3600 - minute * 60);
    if (minute === 0 && second === 0) {
      this.caculateTime2();
      // clearInterval(timer);
    }
    second = second < 10 ? `0${second}` : second;
    minute = minute < 10 ? `0${minute}` : minute;
    const time = `${minute}:${second}`;
    return time;
  }

  caculateTime2 = () => {
    clearInterval(timer);
    const now = moment().valueOf();
    const endDate = moment(this.state.startTime).valueOf();

    let minute = parseInt((now - endDate) / (1000 * 60));
    let second = parseInt(((now - endDate) / (1000)) % 60);
    second = second < 10 ? `0${second}` : second;
    minute = minute < 10 ? `0${minute}` : minute;
    const time = `${minute}:${second}`;
    this.setState({ endTime: time }, () => {
      this.props.endExam(this.state.endTime);
    });
  }

  complete = (isCompelete) => {
    Modal.alert('提交试卷', isCompelete ? `您确定要提交试卷吗？` : `您还有题没做，确定交卷？`, [
      {
        text: '取消',
        onPress: () => {
        },
      },
      { text: '确定', onPress: this.caculateTime2 },
    ]);
  }

  render() {
    const { dispatch, exam } = this.props;
    const item = exam.list[0];
    if (!item) return null;
    const { current, page, pageSize, total, totalCount, totalPageCount } = exam.pagination;

    let { selectKey } = this.state;
    const arr = [];
    for (const i in item.items) {
      arr.push({ label: i, value: item.items[i] });
    }

    const preSelectKey = _.get(_.find(exam.trains, { _id: item._id }), 'selectKey');
    if (preSelectKey) {
      selectKey = preSelectKey;
    }

    return (
      <div className={styles.main}>
        <Helmet>
          <title>
            {this.props.location.query.examLibName}
          </title>
        </Helmet>

        <div className={styles.num}>

          <div className={styles.time}>
            <img src={require('../assets/time.png')} alt="" />
            {this.state.time}
          </div>


          {current !== total ? (<div className={styles.complete} onClick={() => this.complete(current === total)}>
            <span className={styles.btn}>
              <img src={require('../assets/handExam.png')} alt="" />
              交卷
            </span>
          </div>) : null}
        </div>

        <WingBlank>
          <div className={styles.title}>
            <img
              src={require(item.type === false ? '../assets/multiSelection.png' : '../assets/singleSelection.png')}
              alt=""
            />
            {item.question}
          </div>

          <div className={styles.container}>
            {
              arr.map(i =>
                (
                  <div
                    className={classnames({
                      [styles.item]: true,
                      [styles.active]: selectKey.indexOf(i.label) !== -1,
                    })}
                    key={i.label}
                    onClick={() => this.onChange(i.label, item, current + 1, total, selectKey)}
                  >
                    <div
                      className={
                        classnames({
                          [styles.label]: true,
                          [styles.active]: selectKey.indexOf(i.label) !== -1,
                          [styles.circle]: item.type !== false,
                        })
                      }
                    >
                      {
                        selectKey.indexOf(i.label) !== -1 ? '✓' : i.label
                      }
                    </div>
                    <div className={styles.value}>{i.value}</div>
                  </div>
                ))
            }
          </div>
        </WingBlank>
        {current === total ? (<div className={styles.completeBtn} onClick={() => this.complete(current === total)}>
          <img src={require('../assets/handExam.png')} alt="" />
          交卷
        </div>) : null}


        <div className={styles.button}>
          <div
            onClick={() => {
              this.onChangePage(current - 1, total);
            }} className={styles.left}
            style={current === 1 ? { visibility: 'hidden' } : {}}
          >
            上一题
          </div>
          <div className={styles.complete}>
            <img src={require('../assets/examReasult.png')} alt="" />
            <span className={styles.current}>{current}</span>
            <span className={styles.total}>/{total}</span>
          </div>
          <div
            onClick={() => {
              if (current !== total) { this.onChangePage(current + 1, total, selectKey); }
            }}
            className={styles.right}
            style={!selectKey.length ? { visibility: 'hidden' } : {}}
          >
            {current === total ? '结束' : '下一题'}
          </div>
        </div>
      </div>
    );
  }
}


export default connect(
  (state, props) => {
    const examLibName = decodeURIComponent(props.location.query.examLibName);
    const exam_time = props.location.query.exam_time;
    const ref_type = props.location.query.ref_type;
    const ref_id = props.location.query.ref_id;
    const shopId = props.location.query.shopId;
    return {
      exam: state.exam,
      examLibName,
      exam_time,
      ref_type,
      ref_id,
      shopId,
      score: state.exam.score,
    };
  },
  (dispatch, props) => {
    return {
      fetch(payload) {
        dispatch({ type: 'exam/fetch', payload: { ...payload } });
      },
      doExam(selectKey, param, ref_type, ref_id) {
        dispatch({ type: 'exam/doExam', payload: { ...param, selectKey, ref_type, ref_id, type: 'exam' } });
      },
      // getTrains(ref_type, ref_id) {
      //   dispatch({ type: 'exam/getTrains', payload: { ref_type, ref_id, type: 'exam' } });
      // },
      startExam(startTime, ref_type, ref_id) {
        dispatch({ type: 'exam/startExam', payload: { startTime, ref_type, ref_id, type: 'exam', trains: '' } });
      },
      endExam(time) {
        dispatch({ type: 'exam/endExam',
          payload: { time,
            ref_type: props.location.query.ref_type,
            ref_id: props.location.query.ref_id,
            shopId: props.location.query.shopId,
            examLibName: decodeURIComponent(props.location.query.examLibName) },
        });
      },
    };
  },
)(ExamPage);
